package com.lc.alipay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.lc.alipay.config.AliPayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/4 11:43
 */
@Slf4j
@RestController
@RequestMapping("/callback")
public class CallBackController {

    @RequestMapping("/return")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = requestParams.entrySet();
        // 将支付宝GET过来的结果重新封装
        for (Map.Entry<String, String[]> en : entrySet) {
            String[] values = en.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(en.getKey(), valueStr);
        }
        // 同步验证结果
        boolean res = AlipaySignature.certVerifyV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.CHARSET, AliPayConfig.SIGN_TYPE);
        if (res) {
            // 商户订单号
            String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 支付宝交易号
            String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            log.info("订单校验成功。商户订单号：{}，支付宝交易号：{}，支付金额：{} ", outTradeNo, tradeNo, totalAmount);
        }else {
            log.info("订单校验失败");
        }
    }


    @RequestMapping("/notify")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = requestParams.entrySet();
        // 将支付宝GET过来的结果重新封装
        for (Map.Entry<String, String[]> en : entrySet) {
            String[] values = en.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(en.getKey(), valueStr);
        }
        // 异步验证结果
        boolean res = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.CHARSET, AliPayConfig.SIGN_TYPE);
        if (res) {
            JSONObject bizContent = JSON.parseObject(params.get("biz_content"));
            log.info("异步回调内容：{}", bizContent.toString());
            // 交易状态
            String status = bizContent.getString("status");
            log.info("订单交易状态：{}", status);
        }
    }

}
